<?php

namespace app\admin\controller;

use think\Db;
use think\Session;

class Money extends Authorized
{

    public function index()
    {
        $get_data=$this->request->get();
        $time=date('Y-m-d',strtotime('-1 day'));


        $data=[
            'departid'=>3,
            'state'=>0
        ];
        if (Session::get('admin.levelNum')==1){
            $data['id']=Session::get('admin.id');
        }
        $seo=Db::table('tb_admin')->where($data)->select();
        $this->assign('seo', $seo);

        return $this->fetch();


    }
    public function getList()
    {
        $get_data=$this->request->get();
        $post_data = $this->request->post();
        $time=date('Y-m-d',strtotime('-1 day'));

        $page = $get_data['page'];
        $limit = $get_data['limit'];

        $where=[];
        $where['keyid']=['>',0];
        $startTime=input('startTime');
        $endTime=input('endTime');

        if(Session::get('admin.levelNum')==1){
            $where['m.seoid']=Session::get('admin.id');
        }

        if(!empty($startTime) && !empty($endTime)){
            $where['m.intime']=['between time',[$startTime,$endTime]];
        }else{
            if(!empty($startTime)){
                $where['m.intime']=['>=',$startTime];
            }
            if(!empty($endTime)){
                $where['m.intime']=['<=',$endTime];
            }
        }


        $typeid=input('typeid');
        if (!empty($typeid)){$where['m.typeid']=$typeid;}


        $isindex=input('isIndex');
        if (!empty($isindex)){
            if($isindex==1){$where['m.keypm']=['<=',10];}
            if($isindex==2){$where['m.keypm']=['>',10];}
        }


        $keywords=input('keywords');
        if (!empty($keywords)){$where['m.name']=['like','%'.$keywords.'%'];}


        $count=Db::table('tb_money m')->field('m.*,w.url')->join('tb_webinfo w','m.webid = w.id','left')->where($where)->count();
        $sum=Db::table('tb_money m')->field('m.*,w.url')->join('tb_webinfo w','m.webid = w.id','left')->where($where)->sum('money');
        $rows=Db::table('tb_money m')->field('m.*,w.url')
            ->join('tb_webinfo w','m.webid = w.id','left')
            ->where($where)
            ->order('id desc')
            ->page($page, $limit)->select();

        return json(['code' =>0, 'count' =>$count, 'msg' =>'', "totalRow"=>['money'=>$sum], 'data'=>$rows]);
    }

//提现申请
    public function applylist(){return $this->fetch();}
    public function getApplyList()
    {
        $get_data=$this->request->get();
        $page = $get_data['page'];
        $limit = $get_data['limit'];



        $count=Db::table('tb_moneyApply m')->field('m.*,a.money seoMoney')->join('tb_admin a','m.seoid = a.id','left')->count();
        $rows=Db::table('tb_moneyApply m')->field('m.*,a.money seoMoney')->join('tb_admin a','m.seoid = a.id','left')->order('id desc')->page($page, $limit)->select();

        return json(['code' =>0, 'count' =>$count, 'msg' =>'', 'data'=>$rows]);
    }
//


    public function seomoney(){
        $rows=Db::table('tb_admin')->where(['departID'=>3,'state'=>0,'id'=>['>',29]])->select();
        foreach($rows as $k=>$v){
            $moneyThis=Db::table('tb_money')->where(['seoid'=>$v['id'],'qfstate'=>0,'keyid'=>['>',0]])->whereTime('intime', 'month')->sum('money');
            $moneyPre=Db::table('tb_money')->where(['seoid'=>$v['id'],'qfstate'=>0,'keyid'=>['>',0]])->whereTime('intime', 'last month')->sum('money');
            $rows[$k]['moneyThis']=$moneyThis;
            $rows[$k]['moneyPre']=$moneyPre;
        }


        $this->assign('list', $rows);
        return $this->fetch();
    }

//我的钱包
    public function my()
    {

        $post_data = $this->request->post();
        if($post_data){
            $money=$post_data['num'];

            Db::table('tb_moneyApply')->startTrans();
            $id =Db::table('tb_moneyApply')->insertGetId(['seoid'=>Session::get('admin.id'),'seoname'=>Session::get('admin.name'),'name'=>'提现申请-'.$money.'元','money'=>$money,'M_money'=>$money]);
            if (false === $id) {
                Db::table('tb_moneyApply')->rollback();
                return json(['code' =>1,'count' =>0,'msg' =>'添加失败','data'=>'']);
            } else {
                Db::table('tb_moneyApply')->commit();
                return json(['code' =>0,'count' =>0,'msg' =>'申请成功审核中~','data'=>'']);
            }

        }


        $myData=Db::table('tb_admin')->where(['id'=>Session::get('admin.id')])->find();
        $this->assign('myData', $myData);

        $applyList=Db::table('tb_moneyApply')->where(['seoid'=>Session::get('admin.id')])->order('id desc')->select();

        $this->assign('applyList', $applyList);
        return $this->fetch();

    }
    public function getMy()
    {
        $get_data=$this->request->get();

        $page = $get_data['page'];
        $limit = $get_data['limit'];

        $where=[];
        $where['typeid']=['>',0];

        if(Session::get('admin.levelNum')==1){
            $where['seoid']=Session::get('admin.id');
        }

        
        $count=Db::table('tb_Moneyseo')->where($where)->count();
        $rows=Db::table('tb_Moneyseo')->where($where)->order('id desc')->page($page, $limit)->select();

        return json([
            'code' =>0,
            'count' =>$count,
            'msg' =>'',
            'data'=>$rows]);
    }

//客户资金管理
    public function user()
    {
        $post_data = $this->request->post();
        if($post_data){

            $userid=$post_data['id'];
            $money=$post_data['money'];
            $typeid=$post_data['typeid'];

            $res=Db::table('tb_user')->where('id',$post_data['id'])->find();
            if($typeid==0){
//                资金入账
                $czNum=Db::table('tb_Money')->where(['userid'=>$userid])->count();
                if($czNum==0){
                    Db::table('tb_user')->where('id',$res['id'])->update(['money_sc'=>$money]);
                }

//                   欠费时
                if($res['qftime']){
                    if($money+$res['money']>=0){
                        Db::table('tb_user')->where('id',$res['id'])->update(['qftime'=>null]);
                        Db::table('tb_webinfo')->where('userID',$res['id'])->update(['qftime'=>null]);
                        Db::table('tb_webkey')->where('userid',$res['id'])->update(['qftime'=>null]);
                    }
                }

                Db::table('tb_money')->insert(['userID'=>$res['id'], 'typeid'=>$typeid, 'Name'=>'账户充值','money'=>$money]);
                Db::table('tb_user')->where('id',$res['id'])->update(['money'=>Db::raw('money+'.$money), 'money_cz'=>Db::raw('money_cz+'.$money)]);
                return  json(['code' =>0,'count' =>0,'msg' =>'资金入账成功','data'=>'']);
            }else{
//                扣除资金
                $id=Db::table('tb_money')->insertGetId(['userID'=>$res['id'], 'typeid'=>$typeid, 'Name'=>'扣除资金','money'=>$money]);
                Db::table('tb_user')->where('id',$res['id'])->update(['moneypay'=>Db::raw('moneypay+'.$money),'money'=>Db::raw('money-'.$money)]);
                return  json(['code' =>0,'count' =>0,'msg' =>'资金扣除成功','data'=>'']);
            }
        }

        $get_data=$this->request->get();
        $userID = $get_data['userID'];
        $this->assign('userID', $userID);

        $article=Db::table('tb_user')->where('id',$userID)->find();
        $this->assign('article', $article);
        return $this->fetch();
    }
//    账户清零
    public function money_reset(){

        $post_data = $this->request->post();
        if($post_data){
            $result =Db::table('tb_user')->where('id', $post_data['userID'])->setField('money',0);
            if (false === $result) {
                return json(['msg' =>'清零失败', 'code' =>1]);
            } else {
                return json(['msg' =>'清零成功', 'code' =>0]);
            }
        }
    }
//    客户充值记录
    public function usercz(){
        $get_data=$this->request->get();
        $userID = $get_data['userID'];
        $this->assign('userID', $userID);


        $list=Db::table('tb_money')->where(['userid'=>$userID,'typeid'=>0])->order('id desc')->select();
        $this->assign('list', $list);

        return $this->fetch();
    }


//关键词手动扣费页面
    public function keykf(){
        $get_data=$this->request->get();

        $post_data = $this->request->post();
        if($post_data){
            $d=[];
            $money=0;

            $intime =$post_data['intime'].' 22:30:00' ;
            $keypm=$post_data['keypm'];

            $res=Db::table('tb_webkey k')->field('k.*,u.money as user_money')
                ->join('tb_user u','u.id=k.userid')
                ->where('k.id',$post_data['id'])
                ->find();
            if ($keypm<=10){$money=$res['money_one'];}
            if ($keypm>10 && $keypm<=20){$money=$res['money_two'];}


            if($res){
                if($res['user_money']<0){
                    $d['qfstate']=1;
                }
                $d['userID']=$res['userid'];
                $d['webid']=$res['webID'];
                $d['keyid']=$res['id'];
                $d['seoid']=$res['seoid'];
                $d['keypm']=$keypm;
                $d['typeid']=$res['typeid'];
                $d['Name']='seo扣费'.$res['name'];
                $d['money']=$money;
                $d['intime']=$intime;
            }

            $idNum =Db::table('tb_money')->where(['keyid'=>$d['keyid']])->whereTime('intime','between', [$post_data['intime'].' 00:00:00',$post_data['intime'].' 23:59:59'])->count();
            if($idNum==0){
                $id =Db::table('tb_money')->insertGetId($d);
                if (false === $id) {
                    return json(['code' =>1,'count' =>0,'msg' =>'操作失败','data'=>'']);
                } else {
                    Db::table('tb_webkey')->where('id',$res['id'])->update(['moneypay'=>Db::raw('moneypay+'.$money)]);  //更新消费金额
                    Db::table('tb_user')->where('id',$res['userid'])->update(['moneypay'=>Db::raw('moneypay+'.$money), 'money'=>Db::raw('money-'.$money)]);  //更新用户消费金额
                    Db::table('tb_admin')->where('id',$res['seoid'])->update(['M_money'=>Db::raw('M_money+'.$money)]);  //更新优化师金额 +
                    return json(['code' =>0,'count' =>0,'msg' =>'操作成功','data'=>'']);
                }

            }else{
                return json(['code' =>1,'count' =>0,'msg' =>'该关键词当天已有扣费','data'=>'']);
            }
        }

        $keyID = $get_data['keyID'];
        $this->assign('keyID', $keyID);


        $article=Db::table('tb_webkey')->where('id',$keyID)->find();
        $this->assign('article', $article);
        return $this->fetch();

    }


//   关键词返还（单个）
    public function del_money()
    {
        $post_data = $this->request->post();
        if($post_data){
            $res=Db::table('tb_money')->where('id',$post_data['id'])->find();

            Db::table('tb_admin')->where('id',$res['seoid'])->update(['M_money'=>Db::raw('M_money-'.$res['money'])]); //更新优化师钱包 -

            Db::table('tb_money')->where('id',$res['id'])->delete(); //删除扣费明细
            Db::table('tb_webkey')->where('id',$res['keyid'])->update(['moneypay'=>Db::raw('moneypay-'.$res['money'])]); //关键词消费
            Db::table('tb_user')->where('id',$res['userID'])->update(['money'=>Db::raw('money+'.$res['money']), 'moneypay'=>Db::raw('moneypay-'.$res['money']),]); //更新用户钱包

            Db::table('tb_user')->where(['money'=>['>=',0]])->update(['qftime'=>null]);
            return json(['code' =>0,'count' =>0,'msg' =>'返还成功','data'=>'']);

        }
    }
//    关键词批量返还（优化管理- 按优化师，时间，金额返还）
    public function back_money()
    {
        $post_data = $this->request->post();
        if($post_data){

            $seoid=$post_data['seoid'];
            $time=$post_data['time'];
            $money=$post_data['money'];

            $where=[];
            $now=0;
            $msg='';

            $where['keyid']=['>',0];
            if (!empty($seoid)){
                $where['seoid']=$seoid;
            }

            $res=Db::table('tb_money')->where($where)->whereTime('intime','between', [$time.' 00:00:00',$time.' 23:59:59'])->order('money')->select();

            foreach($res as $k=>$v){
                if($now+$v['money']<=$money){
                    Db::table('tb_admin')->where('id',$v['seoid'])->update(['M_money'=>Db::raw('M_money-'.$v['money'])]); //更新优化师钱包 -
                    Db::table('tb_money')->where('id',$v['id'])->delete(); //删除扣费明细
                    Db::table('tb_webkey')->where('id',$v['keyid'])->update(['moneypay'=>Db::raw('moneypay-'.$v['money'])]); //关键词消费
                    Db::table('tb_user')->where('id',$v['userID'])->update(['money'=>Db::raw('money+'.$v['money']), 'moneypay'=>Db::raw('moneypay-'.$v['money']),]); //更新用户钱包

                    Db::table('tb_user')->where(['money'=>['>=',0]])->update(['qftime'=>null]);
                    $msg=$msg.$v['Name'].'扣除成功<br>';
                    $now=$now+$v['money'];
                }else{
                    break;
                }
            }
            return json(['msg' =>$msg, 'code' =>0,'data'=>$res,'now'=>$now,'money'=>$money]);




        }
    }

//    关键词批量返还按id
    public function back_moneyT()
    {

        $post_data = $this->request->post();
        if($post_data){
            $msg='';
            $now=0;
            $ids=explode(",", $post_data['ids']); //正常状态id
            $res=Db::table('tb_money')->whereIn('id',$ids)->select();
            foreach($res as $k=>$v){
                Db::table('tb_admin')->where('id',$v['seoid'])->update(['M_money'=>Db::raw('M_money-'.$v['money'])]); //更新优化师钱包 -
                Db::table('tb_money')->where('id',$v['id'])->delete(); //删除扣费明细
                Db::table('tb_webkey')->where('id',$v['keyid'])->update(['moneypay'=>Db::raw('moneypay-'.$v['money'])]); //关键词消费
                Db::table('tb_user')->where('id',$v['userID'])->update(['money'=>Db::raw('money+'.$v['money']), 'moneypay'=>Db::raw('moneypay-'.$v['money']),]); //更新用户钱包

                Db::table('tb_user')->where(['money'=>['>=',0]])->update(['qftime'=>null]);
                $msg=$msg.$v['Name'].'扣除成功<br>';
                $now=$now+$v['money'];

            }
            return json(['msg' =>$msg, 'code' =>0,'data'=>$res,'now'=>$now]);
        }
    }

//    关键词重复返还
    public function back_moneyRepeat()
    {

        $post_data = $this->request->post();
        if($post_data){
            $msg='';
            $now=0;
            $ids=explode(",", $post_data['ids']); //正常状态id
            $time=$post_data['intime']; //正常状态id


            $res=Db::table('tb_money')->field('keyid,name,count(id) num')
                ->where('keyid','>','0')
                ->whereTime('intime','between',[$time.' 00:00:00',$time.' 23:59:59'])
                ->group('keyid,name')
                ->having('count(id)>1')
                ->select();

            $ids=0;
            foreach($res as $k=>$v){
                $rows=Db::table('tb_money')->whereTime('intime','between',[$time.' 00:00:00',$time.' 23:59:59'])
                    ->where('keyid',$v['keyid'])->select();

                for($i=0;$i<count($rows);$i++)
                {
                    if($i>0){
                        $ids=$ids.','.$rows[$i]['id'];
                        Db::table('tb_admin')->where('id',$rows[$i]['seoid'])->update(['M_money'=>Db::raw('M_money-'.$rows[$i]['money'])]); //更新优化师钱包 -
                        Db::table('tb_money')->where('id',$rows[$i]['id'])->delete(); //删除扣费明细
                        Db::table('tb_webkey')->where('id',$rows[$i]['keyid'])->update(['moneypay'=>Db::raw('moneypay-'.$rows[$i]['money'])]); //关键词消费
                        Db::table('tb_user')->where('id',$rows[$i]['userID'])->update(['money'=>Db::raw('money+'.$rows[$i]['money']), 'moneypay'=>Db::raw('moneypay-'.$rows[$i]['money']),]); //更新用户钱包
//        //
                        Db::table('tb_user')->where(['money'=>['>=',0]])->update(['qftime'=>null]);
                        $msg=$msg.$rows[$i]['Name'].'扣除成功<br>';
//
                        $now=$now+$rows[$i]['money'];
                    }
                }



//
            }
            return json(['msg' =>$msg, 'code' =>0,'data'=>$res,'now'=>$now]);
        }
    }

//    关键词列表(根据webid)
    public function keylist(){
        $get_data=$this->request->get();
        $keyID = $get_data['keyID'];
        $this->assign('keyID', $keyID);


        $sum=Db::table('tb_money')->where('keyid',$keyID)->sum('money');
        $sumMonth=Db::table('tb_money')->where('keyid',$keyID)->whereTime('intime', 'month')->sum('money');

        $this->assign('sum', $sum);
        $this->assign('sumMonth', $sumMonth);
        return $this->fetch();
    }
    public function getKeyList()
    {
        $get_data=$this->request->get();
        $post_data = $this->request->post();

        $page = $get_data['page'];
        $limit = $get_data['limit'];

        $where=[];

        if (!empty($get_data['keyID'])){
            $keyID = $get_data['keyID'];
            $where['keyid']=$keyID;
        }

        $count=Db::table('tb_money')->where($where)->count();
        $sum=Db::table('tb_money')->where($where)->sum('money');
        $rows=Db::table('tb_money')->where($where)->order('id desc')->page($page, $limit)->select();
        return json([
            'code' =>0,
            'count' =>$count,
            'msg' =>'',
            "totalRow"=>['money'=>$sum],
            'data'=>$rows]);
    }
//    关键词列表


}